package person.drf.shop.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import person.drf.common.utils.R;

import java.util.HashMap;
import java.util.Map;


////@ControllerAdvice(basePackages = "person.drf.shop.product.controller")
//@RestControllerAdvice(basePackages = "person.drf.shop.product.controller")
public class ExceptionControllerAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) ->{
            //获取error错误提示
            String message = item.getDefaultMessage();
            //获取错误属性名
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(400,"数据校验错误").put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){

        return R.error();
    }

}
